Python Introduction: Indexing

The range function lets us build a list of numbers.

In [1]:
list(range(1,10))
Out[1]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [5]:
list(range(10, 20,1))
Out[5]:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Notice anything funny?

Python uses this convention everywhere.

In [6]:
a = list(range(10, 20))
type(a)
Out[6]:
list

Let's talk about indexing.

Indexing in Python starts at 0.

In [7]:
a[0]
Out[7]:
10

And goes from there.

In [8]:
a[1]
Out[8]:
11
In [9]:
a[2]
Out[9]:
12

What do negative numbers do?

In [10]:
a[-1]
Out[10]:
19
In [11]:
a[-2]
Out[11]:
18

You can get a sub-list by slicing.

In [12]:
print(a)
print(a[3:7])
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[13, 14, 15, 16]

Start and end are optional.

In [13]:
a[3:]
Out[13]:
[13, 14, 15, 16, 17, 18, 19]
In [14]:
a[:3]
Out[14]:
[10, 11, 12]

Again, notice how the end entry is not included:

In [ ]:
print(a[:3])
print(a[3])

Slicing works on any sequence type! (list, tuple, str, numpy array)

In [ ]:
a = "CS357"
a[-3:]
In [15]:
 
In [ ]:
 
In [ ]: